const toRad = d => d * Math.PI / 180
export function haversine(p1, p2) {
  const R = 6371000
  const dLat = toRad(p2.latitude - p1.latitude)
  const dLng = toRad(p2.longitude - p1.longitude)
  const lat1 = toRad(p1.latitude), lat2 = toRad(p2.latitude)
  const a = Math.sin(dLat/2)**2 + Math.cos(lat1)*Math.cos(lat2)*Math.sin(dLng/2)**2
  return 2 * R * Math.asin(Math.sqrt(a))
}
export function smoothPoint(prev, curr, alpha = 0.2) {
  if (!prev) return curr
  return {
    latitude: prev.latitude + alpha * (curr.latitude - prev.latitude),
    longitude: prev.longitude + alpha * (curr.longitude - prev.longitude)
  }
}
export function isSpeedValid(prev, curr, prevTs, currTs, maxSpeed = 6) {
  if (!prev) return true
  const dt = (currTs - prevTs)/1000
  if (dt <= 0) return false
  const d = haversine(prev, curr)
  return (d/dt) <= maxSpeed
}
